//
//  Tooler.m
//  leo
//
//  Created by 常艳 on 15/8/26.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "Tooler.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import "QRCodeGenerator.h"
@implementation Tooler
+(int)checkNetworkState
{
    NSLog(@"%@,checkNetworkState entered",Tooler_TAG);
    Reachability *wifi=[Reachability reachabilityForLocalWiFi];
    if([wifi currentReachabilityStatus]!=NotReachable)
    {
        NSLog(@"%@,checkNetworkState,has wifi",Tooler_TAG);
        return 1;
    }
    Reachability *conn=[Reachability reachabilityForInternetConnection];
    if([conn currentReachabilityStatus]!=NotReachable)
    {
        NSLog(@"%@,checkNetworkState,has gprs or other",Tooler_TAG);
        return 2;
    }
    NSLog(@"%@,has no network",Tooler_TAG);
    return 3;
    
}
+(NSString *)getUUID
{
    NSLog(@"%@,getUUID entered",Tooler_TAG);
    NSUUID *uuid=[[UIDevice currentDevice] identifierForVendor];
    if(uuid==NULL)
    {
        NSLog(@"%@,getUUID ,uuid is null",Tooler_TAG);
    }
    NSString *deviceId=[uuid UUIDString];
    if(deviceId==NULL)
    {
        NSLog(@"%@,getUUID ,deviceId is null",Tooler_TAG);

    }
    //[[NSUserDefaults standardUserDefaults] valueForKey:@"SBFormattedPhoneNumber"];
    
    
    return deviceId;
}

+(NSString *)getAppVersion
{
    NSLog(@"%@,getAppVersion entered",Tooler_TAG);
    NSString *configPath=[[NSBundle bundleForClass:[self class]] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary *configTalbe=[[NSDictionary alloc] initWithContentsOfFile:configPath];
    if(configTalbe==NULL)
    {
         NSLog(@"%@,getAppVersion entered,config table is null",Tooler_TAG);
        return NULL;
    }
    if(configTalbe!=NULL)
    {
        NSString *appVersion=[configTalbe objectForKey:@"CFBundleShortVersionString"];
        NSLog(@"%@,getAppversion,app version is %@",Tooler_TAG,appVersion);
        return appVersion;
    }
    return NULL;
}
+(NSString *)hashByHmac:(NSString *)key data:(NSString *)data
{
    @try {

        NSLog(@"%@,haskByHmac entered.Secret Key %@ And Data %@",Tooler_TAG, key, data);
        if(data==NULL||[data length]<=0||key==NULL||[key length]<=0)
        {
            NSLog(@"%@,hashByHmac,data or key is null",Tooler_TAG);
            return NULL;
        }
        
        const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
        const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
        
        
        
        unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
        
        CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
        NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                              length:sizeof(cHMAC)];
        if(HMAC==NULL)
        {
            NSLog(@"%@,hashByHmac,HMAC is null",Tooler_TAG);
            return NULL;
        }
        NSString *b64EncStr = [Base64 encodeBase64Data:HMAC];
        NSLog(@"Base 64 encoded = %@",b64EncStr);
        //return [[NSString alloc] initWithData:HMAC encoding:NSASCIIStringEncoding];
        return [self hexStringFromString:b64EncStr];
    }
    @catch (NSException *exception) {
        NSLog(@"%@,hashByHmac,exception info is %@",Tooler_TAG,[exception reason]);
    }
    @finally {
        
    }

    return NULL;
}
+(NSString *)getSystemVersion
{
    return [[UIDevice currentDevice] systemVersion];
}
+ (NSString*)getMachine
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *name = malloc(size);
    sysctlbyname("hw.machine", name, &size, NULL, 0);
    
    NSString *machine = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
    NSLog(@"%@,getMachine,machine is %@,",Tooler_TAG,machine);
    free(name);
    
    if( [machine isEqualToString:@"i386"] || [machine isEqualToString:@"x86_64"] ) machine = @"ios_Simulator";
    else if( [machine isEqualToString:@"iPhone1,1"] ) machine = @"iPhone_1G";
    else if( [machine isEqualToString:@"iPhone1,2"] ) machine = @"iPhone_3G";
    else if( [machine isEqualToString:@"iPhone2,1"] ) machine = @"iPhone_3GS";
    else if( [machine isEqualToString:@"iPhone3,1"] ) machine = @"iPhone_4";
    else if( [machine isEqualToString:@"iPod1,1"] ) machine = @"iPod_Touch_1G";
    else if( [machine isEqualToString:@"iPod2,1"] ) machine = @"iPod_Touch_2G";
    else if( [machine isEqualToString:@"iPod3,1"] ) machine = @"iPod_Touch_3G";
    else if( [machine isEqualToString:@"iPod4,1"] ) machine = @"iPod_Touch_4G";
    else if( [machine isEqualToString:@"iPad1,1"] ) machine = @"iPad_1";
    else if( [machine isEqualToString:@"iPad2,1"] ) machine = @"iPad_2";
    
    return machine;
}

+(NSString *)getTS
{

    NSDate* date = [NSDate date];
    NSTimeInterval interVal=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)interVal];
    //NSString *timeString = [NSString stringWithFormat:@"%ld", (long)interVal];
    return timeString;


}

+(NSString *)getCurrentTimeStamp
{
    NSDate* date = [NSDate date];
    NSTimeInterval interVal=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)interVal];
    return timeString;
}

+(NSString *)getDateTime:(NSString *)timeStamp
{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate* date = [NSDate date];
    NSTimeInterval now=[date timeIntervalSince1970];
    NSInteger today=(int)now/(24*3600);
    long ts=(long)[timeStamp longLongValue];
    NSInteger theday=ts/(24*3600);
    NSInteger diff=today-theday;
    NSString *pre=@"";
    switch (diff) {
        case 0:
            [dateFormatter setDateFormat:@"HH:mm"];
            break;
        case 1:
        {
            [dateFormatter setDateFormat:@"HH:mm"];
            pre=@"昨天 ";
        }
            break;
            
        default:
        {
            [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
        }
            break;
    }
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:ts];
    NSString* strDate=[pre stringByAppendingString:[dateFormatter stringFromDate:theDate]];
    return strDate;
}
+(NSString *)getHistoryDateTime:(NSString *)timeStamp
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate* date = [NSDate date];
    NSTimeInterval now=[date timeIntervalSince1970];
    NSInteger today=(int)now/(24*3600);
    long ts=(long)[timeStamp longLongValue];
    NSInteger theday=ts/(24*3600);
    NSInteger diff=today-theday;
    NSString *pre=@"";
    switch (diff) {
        case 0:
            [dateFormatter setDateFormat:@"HH:mm"];
            break;
        case 1:
        {
            [dateFormatter setDateFormat:@"HH:mm"];
            pre=@"昨天 ";
            return pre;
        }
        break;
            
        default:
        {
            int mondayTs=[self getMondayStamp];
            if(ts>=mondayTs)//本周内
            {
                return [self getweek:timeStamp];
            }
            else
            {
                [dateFormatter setDateFormat:@"YY/MM/dd"];
            }
           
        }
            break;
    }
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:ts];
    NSString* strDate=[pre stringByAppendingString:[dateFormatter stringFromDate:theDate]];
    return strDate;
}
+(int)getMondayStamp{
    NSDate* theDate = [NSDate date];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit|NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit| NSSecondCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    int week = (int)[dateComponent weekday];
    NSInteger hour=[dateComponent hour];
    NSInteger min=[dateComponent minute];
    NSInteger sec=[dateComponent second];
    long mondayTs=0;
    NSTimeInterval timeStamp=[theDate timeIntervalSince1970];
    switch (week) {
        case 1:
            mondayTs=timeStamp-6*24*3600-hour*3600-min*60-sec;
        break;
        case 2:
            mondayTs=timeStamp-hour*3600-min*60-sec;
            break;
        case 3:
            mondayTs=timeStamp-1*24*3600-hour*3600-min*60-sec;
            break;
        case 4:
            mondayTs=timeStamp-2*24*3600-hour*3600-min*60-sec;
            break;
        case 5:
            mondayTs=timeStamp-3*24*3600-hour*3600-min*60-sec;
            break;
        case 6:
            mondayTs=timeStamp-4*24*3600-hour*3600-min*60-sec;
            break;
        case 7:
            mondayTs=timeStamp-5*24*3600-hour*3600-min*60-sec;
            break;
    }
    return mondayTs;
}
+(int)getYear:(NSString *)timeStamp
{
    if(timeStamp==NULL||!([timeStamp intValue]>0))
        return 0;
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    int year = (int)[dateComponent year];
    return year;
}
+(int)getMonth:(NSString *)timeStamp
{
    if(timeStamp==NULL||!([timeStamp intValue]>0))
        return 0;
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    int month = (int)[dateComponent month];
    return month;
}
+(int)getDay:(NSString *)timeStamp
{
    if(timeStamp==NULL||!([timeStamp intValue]>0))
        return 0;
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    int day = (int)[dateComponent day];
    return day;
}



+(NSString *)getweek:(NSString *)timeStamp
{
    if(timeStamp==NULL||!([timeStamp intValue]>0))
        return 0;
    NSArray * arrWeek=[NSArray arrayWithObjects:@"",@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六", nil];
    NSDate *theDate=[NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit|NSWeekdayCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    NSInteger week=[dateComponent weekday];
    return [arrWeek objectAtIndex:week];
}
+(NSString *)getFullName
{
    return [[UIDevice currentDevice] name];
}

+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
    } 
    return hexStr; 
}
+(Role)getManagerType:(int)type
{
    if(type==1)//主管理员
    {
        return ADMIN;
    }
    else
    {
        return VICE_ADMIN;
    }
}
+(Role)getContactType:(int)type
{
    if(type==1)//sos联系人
    {
        return SOS_CONTACT;
    }
    else
    {
        return CONTACT;
    }
}
+(int)getContactValue:(Role)role
{
    if(role==SOS_CONTACT)
        return 1;
    else
        return 0;
}
+(int)getManagerValue:(Role)role
{
    if(role==ADMIN)
        return 1;
    else
        return 0;
}
+ (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
+(NSString *)getCurrentTime
{
    NSString* date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    date = [formatter stringFromDate:[NSDate date]];
    return date;
}
+(NSString *)getTimeStamp
{
    NSDate* date = [NSDate date];
    NSTimeInterval interVal=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)interVal];
    return timeString;;
}

+(NSString *)strToTime:(NSString *)dateStr
{
    NSString *ts=NULL;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"utc"];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date=[formatter dateFromString:dateStr];
    dateStr=NULL;
    ts=[NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    return ts;
}
+(NSString *)strToLocalTime:(NSString *)dateStr//转换成时间戳以后会少8小时
{
    NSString *ts=NULL;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"utc"];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date=[formatter dateFromString:dateStr];
    dateStr=NULL;
    ts=[NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]+8*3600];
    return ts;
}
+(NSString *)infoFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"=======%@",documentsDirectory);
    return [documentsDirectory stringByAppendingPathComponent:@"info.plist"];
}
+(long)getCheckAppUpdateTime
{
    NSLog(@"%@,getCheckAppUpdateTime entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getCheckAppUpdateTime,not find the  file,return 0",Tooler_TAG);
        return -1;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getCheckAppUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSNumber *updateTime=[dict objectForKey:@"CHECK_APP_UPDATE_TIME"];
        if(updateTime==NULL)
        {
            NSLog(@"%@,getCheckAppUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSLog(@"%@,getCheckAppUpdateTime,version number is %@",Tooler_TAG,updateTime);
        return  (long)[updateTime longLongValue];
    }
}

+(BOOL)updateCheckAppUpdateTime:(long)updateTime
{
    NSLog(@"%@,updateCheckAppUpdateTime entered,updateTime is %ld.",Tooler_TAG,updateTime);
    NSString *configPath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:configPath];
    NSMutableDictionary *dict=NULL;
    if(find==NO)//文件不存在，创建文件，并将版本号写入
    {
        [fileManager createFileAtPath:configPath contents:nil attributes:nil];
        dict=[[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%ld",updateTime] forKey:@"CHECK_APP_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    else//读取版本号，并修改版本号
    {
        dict=[[[NSMutableDictionary alloc] initWithContentsOfFile:configPath] mutableCopy];
        NSNumber *appUpdateTime=[dict objectForKey:@"CHECK_APP_UPDATE_TIME"];
        appUpdateTime=[NSNumber numberWithLong:updateTime];
        [dict setObject:appUpdateTime forKey:@"CHECK_APP_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    return YES;
    
}

+(long)getCheckWatchUpdateTime
{
    NSLog(@"%@,getCheckWatchUpdateTime entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getCheckWatchUpdateTime,not find the  file,return 0",Tooler_TAG);
        return -1;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getCheckWatchUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSNumber *updateTime=[dict objectForKey:@"CHECK_WATCH_UPDATE_TIME"];
        if(updateTime==NULL)
        {
            NSLog(@"%@,getCheckWatchUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSLog(@"%@,getCheckWatchUpdateTime,version number is %@",Tooler_TAG,updateTime);
        return  [updateTime longValue];
    }
}

+(BOOL)updateCheckWatchUpdateTime:(long)updateTime
{
    NSLog(@"%@,updateCheckWatchUpdateTime entered,updateTime is %ld.",Tooler_TAG,updateTime);
    NSString *configPath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:configPath];
    NSMutableDictionary *dict=NULL;
    if(find==NO)//文件不存在，创建文件，并将版本号写入
    {
        [fileManager createFileAtPath:configPath contents:nil attributes:nil];
        dict=[[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%ld",updateTime] forKey:@"CHECK_APP_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    else//读取版本号，并修改版本号
    {
        dict=[[[NSMutableDictionary alloc] initWithContentsOfFile:configPath] mutableCopy];
        NSNumber *appUpdateTime=[dict objectForKey:@"CHECK_WATCH_UPDATE_TIME"];
        appUpdateTime=[NSNumber numberWithLong:updateTime];
        [dict setObject:appUpdateTime forKey:@"CHECK_WATCH_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    return YES;
    
}

+(BOOL)updateDeviceUid:(int)deviceUid
{
    NSLog(@"%@,updateDeviceUid entered.",Tooler_TAG);
    NSString *configPath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:configPath];
    NSMutableDictionary *dict=NULL;
    if(find==NO)//文件不存在，创建文件，并将版本号写入
    {
        NSLog(@"%@,updateDeviceUid,not find info file",Tooler_TAG);
        [fileManager createFileAtPath:configPath contents:nil attributes:nil];
        dict=[[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%d",deviceUid] forKey:@"DEVICE_UID"];
        [dict writeToFile:configPath atomically:YES];
    }
    else//读取版本号，并修改版本号
    {
        NSLog(@"%@,updateDeviceUid, find info file",Tooler_TAG);
        dict=[[[NSMutableDictionary alloc] initWithContentsOfFile:configPath] mutableCopy];
        NSNumber *versionValue=[dict objectForKey:@"DEVICE_UID"];
        versionValue=[NSNumber numberWithInt:deviceUid];
        [dict setObject:versionValue forKey:@"DEVICE_UID"];
        [dict writeToFile:configPath atomically:YES];
    }
    NSLog(@"%@,updateDeviceUid,update version sucess,version number is %d",Tooler_TAG,deviceUid);
    return YES;
    
}
+(int) getGroupId
{
    NSLog(@"%@,getGroupId entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getGroupId,not find the version file,return 0",Tooler_TAG);
        return -1;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getGroupId,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSNumber *versionNumber=[dict objectForKey:@"GROUP_ID"];
        if(versionNumber==NULL)
        {
            NSLog(@"%@,getGroupId,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSLog(@"%@,getGroupId,version number is %@",Tooler_TAG,versionNumber);
        return  [versionNumber intValue];
    }
}
+(int) getDeviceUid
{
    NSLog(@"%@,getDeviceUid entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getDeviceUid,not find the version file,return 0",Tooler_TAG);
        return -1;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getDeviceUid,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSNumber *versionNumber=[dict objectForKey:@"DEVICE_UID"];
        if(versionNumber==NULL)
        {
            NSLog(@"%@,getDeviceUid,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSLog(@"%@,getDeviceUid,version number is %@",Tooler_TAG,versionNumber);
        return  [versionNumber intValue];
    }
}
+(NSString *)getDocumentDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}
+(BOOL)isDirectoryExist:(NSString *)directoryPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(fileManager==NULL)
    {
        NSLog(@"%@,isDirectoryExist,fileManager is null.",Tooler_TAG);
        return NO;
    }
    BOOL find = [fileManager fileExistsAtPath:directoryPath];
    if(find)
    {
        NSLog(@"%@,isDirectoryExist,directory already exist.",Tooler_TAG);
    }
    else
    {
        NSError *error;
        [fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
        if(error!=nil)
        {
            NSLog(@"%@,isDirectoryExist,create directory error, error is %@.",Tooler_TAG,error);
            return NO;
        }
    }
    return YES;
}
+(NSString *)getFenceName:(int) type
{
    NSString *fenceName=NULL;
    switch (type) {
        case 1:
            fenceName=@"学校";
            break;
        case 2:
            fenceName=@"家";
            break;
        default:
            break;
    }
    return fenceName;
}
+(int)getGradeNumber:(NSString *)greadeStr
{
   if([greadeStr isEqualToString:@"未上学"])
       return 0;
    else if([greadeStr isEqualToString:@"幼儿园小班"])
        return 1;
    else if([greadeStr isEqualToString:@"幼儿园中班"])
        return 2;
    else if([greadeStr isEqualToString:@"幼儿园大班"])
        return 3;
    else if([greadeStr isEqualToString:@"一年级"])
        return 4;
    else if([greadeStr isEqualToString:@"二年级"])
        return 5;
    else if([greadeStr isEqualToString:@"三年级"])
        return 6;
    else if([greadeStr isEqualToString:@"四年级"])
        return 7;
    else if([greadeStr isEqualToString:@"五年级"])
        return 8;
    else if([greadeStr isEqualToString:@"六年级"])
        return 9;
    else if([greadeStr isEqualToString:@"七年级"])
        return 10;
    else if([greadeStr isEqualToString:@"八年级"])
        return 11;
    else if([greadeStr isEqualToString:@"九年级"])
        return 12;
    else if([greadeStr isEqualToString:@"自定义"])
        return 13;
    else return 0;
    
}
+(UIImage *)getQrcodeUrl:(NSString *)deviceUid imei:(NSString *)imei size:(CGFloat)size
{
    if(deviceUid==NULL||imei==NULL)
    {
        NSLog(@"%@,getQrcodeUrl,deviceUid is null.",Tooler_TAG);
        return NULL;
    }
    //获取手表imei号，和qrcoeurl
    NSString *qrcodeData=[NSString stringWithFormat:@"%@;%@;00000000",imei,deviceUid];
    UIImage *qrcodeImg=[QRCodeGenerator qrImageForString:qrcodeData imageSize:size];
    return qrcodeImg;
   
}
+(int)getLevelNum:(int)semp
{
   if(semp<1)
       return 0;
    else if(semp<6)
        return 1;
    else if(semp<16)
        return 2;
    else if(semp<31)
        return 3;
    else if(semp<51)
        return 4;
    else if(semp<81)
        return 5;
    else if(semp<121)
        return 6;
    else if(semp<171)
        return 7;
    else if(semp<231)
        return 8;
    else if(semp<301)
        return 9;
    else if(semp<381)
        return 10;
    else if(semp<471)
        return 11;
    else if(semp<571)
        return 12;
    else if(semp<681)
        return 13;
    else if(semp<801)
        return 14;
    else
        return 15;
        
}
 
+(float)getProgressRate:(int)semp
{
    if(semp<1)
        return semp/1.0;
    else if(semp<6)
        return (semp-1)/5.0;
    else if(semp<16)
        return (semp-6)/10.0;
    else if(semp<31)
        return (semp-16)/15.0;
    else if(semp<51)
        return (semp-31)/20.0;
    else if(semp<81)
        return (semp-51)/30.0;
    else if(semp<121)
        return (semp-81)/40.0;
    else if(semp<171)
        return (semp-121)/50.0;
    else if(semp<231)
        return (semp-171)/60.0;
    else if(semp<301)
        return (semp-231)/70.0;
    else if(semp<381)
        return (semp-301)/80.0;
    else if(semp<471)
        return (semp-381)/90.0;
    else if(semp<571)
        return (semp-471)/100.0;
    else if(semp<681)
        return (semp-571)/110.0;
    else if(semp<801)
        return (semp-681)/120.0;
    else return 1;
}

+(long)getGrowthUpdateTime
{
    NSLog(@"%@,getGrowthUpdateTime entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getGrowthUpdateTime,not find the  file,return 0",Tooler_TAG);
        return -1;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getGrowthUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSNumber *updateTime=[dict objectForKey:@"GROWTH_UPDATE_TIME"];
        if(updateTime==NULL)
        {
            NSLog(@"%@,getGrowthUpdateTime,dict is null,return 0",Tooler_TAG);
            return -1;
        }
        NSLog(@"%@,getGrowthUpdateTime,version number is %@",Tooler_TAG,updateTime);
        return  (long)[updateTime longLongValue];
    }
}

+(BOOL)updateGrowthUpdateTime:(long)updateTime
{
    NSLog(@"%@,updateGrowthUpdateTime entered,updateTime is %ld.",Tooler_TAG,updateTime);
    NSString *configPath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:configPath];
    NSMutableDictionary *dict=NULL;
    if(find==NO)//文件不存在，创建文件，并将版本号写入
    {
        [fileManager createFileAtPath:configPath contents:nil attributes:nil];
        dict=[[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%ld",updateTime] forKey:@"GROWTH_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    else//读取版本号，并修改版本号
    {
        dict=[[[NSMutableDictionary alloc] initWithContentsOfFile:configPath] mutableCopy];
        NSNumber *appUpdateTime=[dict objectForKey:@"GROWTH_UPDATE_TIME"];
        appUpdateTime=[NSNumber numberWithLong:updateTime];
        [dict setObject:appUpdateTime forKey:@"GROWTH_UPDATE_TIME"];
        [dict writeToFile:configPath atomically:YES];
    }
    return YES;
    
}
+(BOOL)istaskExpire:(Task *)task
{
    if(task==NULL||task.expireTs<=0)
        return NO;
    long now=(long)[[Tooler getCurrentTimeStamp] longLongValue];
    //if((now-[task.createTime longLongValue])>task.expireTs)
    if(now >=task.expireTs)
        return YES;
    else
        return NO;
}
+(NSString *)getRandomCode
{
    NSString *strRandom = @"";
    for(int i=0; i<6; i++)
    {
        strRandom = [ strRandom stringByAppendingFormat:@"%i",(arc4random() % 9)];
    }
    return strRandom;
}
+(NSString *)second2Stringformat:(NSString *)second withFormatter:(NSString *)formatter
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:[second doubleValue]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:formatter];
    
    return [dateFormatter stringFromDate:date];
}
+(BOOL)checkStringBegin:(NSString *)str
{
    if(str==NULL||[str length]==0)
        return NO;
    NSString *begin=[str substringToIndex:1];
    if(begin==NULL||![begin isEqualToString:@"1"])
        return NO;
    return YES;
}
//1 含有除下划线以外其他字符  2长度超出范围  3纯符号/数字 0合法可用
+(int)checkStringIllegal:(NSString *)testString ChnLength:(int)ChnLength EngLength:(int)EngLength
{
    BOOL hasEng=NO; BOOL hasChn=NO;BOOL hasNum=NO;BOOL hasUnderLine=NO;
    BOOL hasIllegal=NO;
    for (int i = 0; i<testString.length; i++) {
        char commitChar = [testString characterAtIndex:i];
        int charvalue=[testString characterAtIndex:i];
        NSString *temp = [testString substringWithRange:NSMakeRange(i,1)];
        const char *u8Temp = [temp UTF8String];
        if (u8Temp!=NULL&&3==strlen(u8Temp)&& (charvalue >= 0x4e00 && charvalue <= 0x9fff)){
            hasChn=YES;
        }else if((commitChar>64)&&(commitChar<91)){
            hasEng=YES;
        }else if((commitChar>96)&&(commitChar<123)){
            hasEng=YES;
        }else if((commitChar>47)&&(commitChar<58)){
            hasNum=YES;
        }else if([temp isEqualToString:@"_"])
            hasUnderLine=YES;
        else
            hasIllegal=YES;
    }
    if(hasIllegal)
        return 1;
    if(hasChn &&[testString length]>ChnLength)
        return 2;
    if(!hasChn&&[testString length]>EngLength)
        return 2;
    if(!hasEng&&!hasChn)
        return 3;
    return 0;
}
+(NSString *)getIdentifier
{
    NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return identifierStr;
}
+ (NSString *)validateNumber:(NSString*)number {
    if(number==NULL)
        return NULL;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            number=[number stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@""];
        }
        else
        {
            i++;
        }
    }
    return number;
    
}
+(long)getTodayStartTs
{
    NSDate* theDate = [NSDate date];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit|NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit| NSSecondCalendarUnit;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
    NSInteger hour=[dateComponent hour];
    NSInteger min=[dateComponent minute];
    NSInteger sec=[dateComponent second];
    NSTimeInterval timeStamp=[theDate timeIntervalSince1970];
    long startTS=timeStamp-hour*3600-min*60-sec;
    return startTS;
}
+(void)showHttpMsg:(SyncResult)result description:(NSString *)description msg:(NSString *)msg
{
    if(result==NODATA)
    {
        [LeoMsg showMsg:@"当前网络异常，请检查网络"];
    }
    else
    {
        if(description!=NULL)
            [LeoMsg showMsg:description];
        else
        {
            if(msg!=NULL)
                [LeoMsg showMsg:msg];
        }
    }
}
+(void)showHttpToast:(SyncResult)result description:(NSString *)description msg:(NSString *)msg parentView:(UIView *)parentView showPosition:(enum ToastShowPosition)position hideAfterDelay:(int)second
{
    if(result==NODATA)
    {
        [LeoMsg showToastMsg:@"当前网络异常，请检查网络" parentView:parentView showPosition:position hideAfterDelay:second];
    }
    else
    {
        if(description!=NULL)
             [LeoMsg showToastMsg:description parentView:parentView showPosition:position hideAfterDelay:second];
        else
        {
            if(msg!=NULL)
               [LeoMsg showToastMsg:msg parentView:parentView showPosition:position hideAfterDelay:second];
        }
    }
}

+(NSString *)getAccountName
{
    NSLog(@"%@,getAccountName entered",Tooler_TAG);
    NSString *filePath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:filePath];
    if(find==NO)
    {
        NSLog(@"%@,getAccountName,not find the  file,return 0",Tooler_TAG);
        return NULL;
    }
    else
    {
        NSDictionary *dict=[[NSDictionary alloc]  initWithContentsOfFile:filePath];
        if(dict==NULL)
        {
            NSLog(@"%@,getAccountName,dict is null,return 0",Tooler_TAG);
            return NULL;
        }
        NSString *accountName=[dict objectForKey:@"ACCOUNT_NAME"];
        if(accountName==NULL)
        {
            NSLog(@"%@,getAccountName,dict is null,return 0",Tooler_TAG);
            return NULL;
        }
        NSLog(@"%@,getAccountName,version number is %@",Tooler_TAG,accountName);
        return  accountName;
    }
}

+(BOOL)updateAccountName:(NSString *)phone
{
    NSLog(@"%@,updateAccountName entered,updateTime is %@.",Tooler_TAG,phone);
    NSString *configPath=[self infoFilePath];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:configPath];
    NSMutableDictionary *dict=NULL;
    if(find==NO)//文件不存在，创建文件，并将版本号写入
    {
        [fileManager createFileAtPath:configPath contents:nil attributes:nil];
        dict=[[NSMutableDictionary alloc] init];
        [dict setObject:[NSString stringWithFormat:@"%@",phone] forKey:@"ACCOUNT_NAME"];
        [dict writeToFile:configPath atomically:YES];
    }
    else//读取版本号，并修改版本号
    {
        dict=[[[NSMutableDictionary alloc] initWithContentsOfFile:configPath] mutableCopy];
        NSString *accountName=[dict objectForKey:@"ACCOUNT_NAME"];
        accountName=[NSString stringWithFormat:@"%@",phone];
        [dict setObject:accountName forKey:@"ACCOUNT_NAME"];
        [dict writeToFile:configPath atomically:YES];
    }
    return YES;
    
}







/////////////////////////////////////UI更改
+ (NSString *)getMonthAndDay:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:date] intValue];
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:date] intValue];
    NSString *finalDate = [NSString stringWithFormat:@"%d月%d日",month,day];
    return finalDate;
}

+ (NSMutableAttributedString *)setFont:(UIFont *)font range:(NSRange)range text:(NSString *)string
{
    NSAttributedString *str = [[NSAttributedString alloc]initWithString:string];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc]initWithAttributedString:str];
    [text addAttribute:NSFontAttributeName value:font range:range];
    
    return text;
}

+ (NSString *)getDate:(NSString *)timeStamp
{

    NSTimeInterval time=[timeStamp doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    return currentDateStr;
    
}

+ (CGFloat)getHeightWithContent:(NSString *)content width:(CGFloat)width font:(CGFloat)font{
    
    CGRect rect = [content boundingRectWithSize:CGSizeMake(width, 999)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                        context:nil];
    return rect.size.height;
}

+ (CGFloat)getCurrentHour
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH"];
    NSString *currentTime = [formatter stringFromDate:date];
    return     currentTime.floatValue;
    
    
}
+ (CGFloat)getCurrentMinutes
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"mm"];
    NSString *currentTime = [formatter stringFromDate:date];
    return     currentTime.floatValue;
    
    
}

@end
